<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Python dictionaries</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, language, programming, learn Python, data types, dictionaries">
<meta name="description" content="In this chapter of the Python tutorial,
we will work with dictionaries.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Python dictionaries</h1>

<p>
In this part of the Python programming tutorial, we will cover Python dictionaries
in more detail.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
<b>Python dictionary</b> is a container of key-value pairs. It is mutable and 
can contain mixed types. A dictionary is an unordered collection. 
Python dictionaries are called associative arrays or hash tables in other languages.
The keys in a dictionary must be immutable objects like strings or numbers. They
must also be unique within a dictionary.
</p>


<h2>Creating dictionaries</h2>

<p>
First, we will show how to create Python dictionaries. 
</p>

<pre class="code">
#!/usr/bin/python

weekend = { "Sun": "Sunday", "Mon": "Monday" }
vals = dict(one=1, two=2)

capitals = {}
capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"

d = { i: object() for i in range(4) }

print weekend
print vals
print capitals
print d
</pre>

<p>
In the example, we create four dictionaries. In four different ways. Later
we print the contents of these dictionaries to the console. 
</p>

<pre class="explanation">
weekend = { "Sun": "Sunday", "Mon": "Monday" }
</pre>

<p>
We create a weekend dictionary using dictionary literal notation.
The key-value pairs are enclosed by curly brackets. The pairs are separated
by commas. The first value of a pair is a key, which is followed by 
a colon character and a value. The "Sun" string is a key and the "Sunday"
string is a value. 
</p>

<pre class="explanation">
vals = dict(one=1, two=2)
</pre>

<p>
Dictionaries can be created using the <code>dict()</code> function.
</p>

<pre class="explanation">
capitals = {}
capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"
</pre>

<p>
This is the third way. An empty capitals dictionary is created. Three
pairs are added to the dictionary. The keys are inside the square brackets,
the values are located on the right side of the assignment. 
</p>

<pre class="explanation">
d = { i: object() for i in range(4) }
</pre>

<p>
A dictionary is created using a dictionary comprehension. The comprehension
has two parts. The first part is the <code>i: object()</code> expression, which
is executed for each cycle of a loop. The second part is the <code>for i in range(4)</code>
loop. The dictionary comprehension creates a dictionary having four pairs, where the
keys are numbers 0, 1, 2, 3 and the values are simple objects. 
</p>

<pre>
$ ./create_dict.py 
{'Sun': 'Sunday', 'Mon': 'Monday'}
{'two': 2, 'one': 1}
{'svk': 'Bratislava', 'dnk': 'Copenhagen', 'deu': 'Berlin'}
{0: &lt;object object at 0xb76cb4a8&gt;, 1: &lt;object object at 0xb76cb4b0&gt;, 
2: &lt;object object at 0xb76cb4b8&gt;, 3: &lt;object object at 0xb76cb4c0&gt;}
</pre>


<h2>Basic operations</h2>


<p>
The following examples will show some basic operations with 
Python dictionaries.
</p>

<pre class="code">
#!/usr/bin/python

basket = { 'oranges': 12, 'pears': 5, 'apples': 4 }

basket['bananas'] = 5

print basket
print "There are %d various items in the basket" % len(basket)

print basket['apples']
basket['apples'] = 8
print basket['apples']

print basket.get('oranges', 'undefined')
print basket.get('cherries', 'undefined')
</pre>

<p>
We have a basket with different fruits. We perform some
operations on the basket dictionary. 
</p>

<pre class="explanation">
basket = { 'oranges': 12, 'pears': 5, 'apples': 4 }
</pre>

<p>
The basket dictionary is created. It has initially three
key-value pairs. 
</p>

<pre class="explanation">
basket['bananas'] = 5
</pre>

<p>
A new pair is created. The 'bananas' string is a key,
the 5 integer is the value. 
</p>

<pre class="explanation">
print "There are %d various items in the basket" % len(basket)
</pre>

<p>
The <code>len()</code> function gives the number of pairs in the
dictionary. 
</p>

<pre class="explanation">
print basket['apples']
</pre>

<p>
The value of the 'apples' key is printed to the terminal. 
</p>

<pre class="explanation">
basket['apples'] = 8
</pre>

<p>
The value of the 'apples' key is modified. It is set to number 8.
</p>

<pre class="explanation">
print basket.get('oranges', 'undefined')
</pre>

<p>
The <code>get()</code> method retrieves the value of a specified key.
If there is no such a key, the second parameter of the method is 
returned. 
</p>

<pre class="explanation">
print basket.get('cherries', 'undefined')
</pre>

<p>
This line returns 'undefined'. There are no cherries in the
basket. 
</p>

<pre>
$ ./basics.py
{'bananas': 5, 'pears': 5, 'oranges': 12, 'apples': 4}
There are 4 various items in the basket
4
8
12
undefined
</pre>

<p>
Example output. 
</p>


<hr class="btm">

<p>
The next example will present two dictionary methods.
The <code>fromkeys()</code> and the <code>setdefault()</code>
method.
</p>

<pre class="code">
#!/usr/bin/python

basket = ('oranges', 'pears', 'apples', 'bananas')

fruits = {}.fromkeys(basket, 0)
print fruits

fruits['oranges'] = 12
fruits['pears'] = 8
fruits['apples'] = 4

print fruits.setdefault('oranges', 11)
print fruits.setdefault('kiwis', 11)

print fruits
</pre>

<p>
The <code>fromkeys()</code> method creates a new dictionary from a
list. The <code>setdefault()</code> method returns a value, if a key
is present. Otherwise it inserts a key with a specified default value and
returns the value. 
</p>

<pre class="explanation">
basket = ('oranges', 'pears', 'apples', 'bananas')
</pre>

<p>
We have a list of strings. From this list a new dictionary will be
constructed. 
</p>

<pre class="explanation">
fruits = {}.fromkeys(basket, 0)
</pre>

<p>
The <code>fromkeys()</code> method creates a new dictionary, where
the list items will be the keys. Each key will be initiated to 0.
Note that the <code>fromkeys()</code> method is a class method and
needs the class name, which is {} in our case, to be called. 
</p>

<pre class="explanation">
fruits['oranges'] = 12
fruits['pears'] = 8
fruits['apples'] = 4
</pre>

<p>
Here we add some values to the fruits dictionary.
</p>

<pre class="explanation">
print fruits.setdefault('oranges', 11)
print fruits.setdefault('kiwis', 11)
</pre>

<p>
The first line prints 12 to the terminal. The 'oranges' key exists in 
the dictionary. In such a case, the method returns the its value. 
In the second case, the key does not exist yet. A new pair 'kiwis': 11 is
inserted to the dictionary. And value 11 is printed to the console. 
</p>

<pre>
$ ./fruits.py 
{'bananas': 0, 'pears': 0, 'oranges': 0, 'apples': 0}
12
11
{'kiwis': 11, 'bananas': 0, 'pears': 8, 'oranges': 12, 'apples': 4}
</pre>

<p>
We receive this output, when we launch the fruits.py script. 
</p>

<hr class="btm">

<p>
The next code example will show, how to add two Python dictionaries.
</p>

<pre class="code">
#!/usr/bin/python

domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary"}
domains2 = { "us": "United States", "no": "Norway" }

domains.update(domains2)

print domains
</pre>

<p>
We have two dictionaries. They are joined with the <code>update()</code>
method. 
</p>

<pre class="explanation">
domains.update(domains2)
</pre>

<p>
The domains2 dictionary is added to the domains dictionary with the
<code>update()</code> method. 
</p>

<pre>
$ ./domains.py
{'sk': 'Slovakia', 'de': 'Germany', 'no': 'Norway', 
'us': 'United States', 'hu': 'Hungary'}
</pre>

<p>
The result shows all values from both dictionaries.
</p>

<hr class="btm">

<p>
Now we will show, how to remove a pair from a dictionary. 
</p>

<pre class="code">
#!/usr/bin/python

items = { "coins": 7, "pens": 3, "cups": 2, 
    "bags": 1, "bottles": 4, "books": 5 }

print items    

items.pop("coins")
print items

del items["bottles"]
print items

items.clear()
print items
</pre>

<p>
The items dictionary has 6 key-value pairs. We will delete pairs 
from this dictionary. 
</p>

<pre class="explanation">
items.pop("coins")
</pre>

<p>
The <code>pop()</code> method removes a pair with a specified key. 
</p>

<pre class="explanation">
del items["bottles"]
</pre>

<p>
The <code>del</code> keyword deletes a "bottles": 4 pair from the
items dictionary.
</p>

<pre class="explanation">
items.clear()
</pre>

<p>
The <code>clear()</code> method clears all items from the dictionary.
</p>

<pre>
$ ./removing.py 
{'bags': 1, 'pens': 3, 'coins': 7, 'books': 5, 'bottles': 4, 'cups': 2}
{'bags': 1, 'pens': 3, 'books': 5, 'bottles': 4, 'cups': 2}
{'bags': 1, 'pens': 3, 'books': 5, 'cups': 2}
{}
</pre>

<p>
Example output. 
</p>


<h2>Keys and values</h2>

<p>
A Python dictionary consists of key-value pairs. The 
<code>keys()</code> method returns a list of keys from a dictionary.
The <code>values()</code> method creates a list of values. And the
<code>items()</code> method returns a list of key-value tuples. 
</p>

<pre class="code">
#!/usr/bin/python

domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }

print domains.keys()
print domains.values()
print domains.items()

print "de" in domains
print "cz" in domains
</pre>

<p>
We demonstrate the above mentioned methods. We also check if a key is
present with the <code>in</code> keyword. 
</p>

<pre class="explanation">
print domains.keys()
</pre>

<p>
We print the list of keys of a domains dictionary with the 
<code>keys()</code> method.
</p>

<pre class="explanation">
print domains.values()
</pre>

<p>
We print the list of values of a domains dictionary with the 
<code>values()</code> method.
</p>

<pre class="explanation">
print domains.items()
</pre>

<p>
And finally, we print the list of key-value tuples of a domains dictionary using the 
<code>items()</code> method.
</p>

<pre class="explanation">
print "de" in domains
print "cz" in domains
</pre>

<p>
With the <code>in</code> keyword, we check if the "de", "cz" keys are 
present in the domains dictionary. The return value is either True or
False. 
</p>

<pre>
$ ./keys_values.py
['sk', 'de', 'no', 'us', 'hu']
['Slovakia', 'Germany', 'Norway', 'United States', 'Hungary']
[('sk', 'Slovakia'), ('de', 'Germany'), ('no', 'Norway'), 
('us', 'United States'), ('hu', 'Hungary')]
True
False
</pre>

<p>
Output of the example.
</p>


<h2>Looping</h2>

<p>
Looping through the dictionary is a common programming job. 
This can be done with the for keyword. 
</p>

<pre class="code">
#!/usr/bin/python

domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }

for key in domains:
    print key
    
for k in domains:
    print domains[k]
    
for k, v in domains.items():
    print ": ".join((k, v))
</pre>

<p>
In the example, we traverse the domains dictionary to print
the keys, values and both keys and values of the dictionary.
</p>

<pre class="explanation">
for key in domains:
    print key
</pre>

<p>
This loop prints all the keys of the dictionary.
</p>

<pre class="explanation">
for k in domains:
    print domains[k]
</pre>

<p>
The second loop prints all values of the dictionary. 
</p>

<pre class="explanation">
for k, v in domains.items():
    print ": ".join((k, v))
</pre>

<p>
In the final loop, all keys and values are printed.
</p>

<pre>
$ ./looping.py
sk
de
no
us
hu
Slovakia
Germany
Norway
United States
Hungary
sk: Slovakia
de: Germany
no: Norway
us: United States
hu: Hungary
</pre>

<p>
Output of the example.
</p>

<h2>Sorting</h2>

<p>
Python dictionaries are orderless. This also implies that they cannot be sorted like
a Python list. Programmers can create sorted representations of Python dictionaries. 
In this section, we will show several ways to create a sorted output. 
</p>

<p>
Programmers might want to sort the data in a normal or reverse order. They could
sort the data by keys or by values. 
</p>


<pre class="code">
#!/usr/bin/python

items = { "coins": 7, "pens": 3, "cups": 2, 
    "bags": 1, "bottles": 4, "books": 5 }
    
kitems = items.keys()
kitems.sort()

for k in kitems:
    print ": ".join((k, str(items[k])))
</pre>

<p>
The first example provides the simplest solution to have the data sorted
by the keys. 
</p>

<pre class="explanation">
kitems = items.keys()
kitems.sort()
</pre>

<p>
A list of keys is obtained from the dictionary. The list is sorted with
the <code>sort()</code> method. 
</p>

<pre class="explanation">
for k in kitems:
    print ": ".join((k, str(items[k])))
</pre>

<p>
In the loop we print the sorted keys together with their values
from the dictionary. 
</p>

<pre>
$ ./simplesort.py
bags: 1
books: 5
bottles: 4
coins: 7
cups: 2
pens: 3
</pre>

<p>
The items dictionary is sorted by its keys.
</p>

<hr class="btm">

<p>
More efficient sorting can be done with the 
built-in <code>sorted()</code> function. 
</p>

<pre class="code">
#!/usr/bin/python

items = { "coins": 7, "pens": 3, "cups": 2, 
    "bags": 1, "bottles": 4, "books": 5 }
    
for key in sorted(items.iterkeys()):
    print "%s: %s" % (key, items[key])

print "####### #######"    
    
for key in sorted(items.iterkeys(), reverse=True):
    print "%s: %s" % (key, items[key])
</pre>

<p>
In the example we print sorted data by their keys in ascending and
descending order using the <code>sorted()</code> function. 
</p>

<pre class="explanation">
for key in sorted(items.iterkeys()):
    print "%s: %s" % (key, items[key])
</pre>

<p>
In this for loop, we print the pairs sorted in ascending order. 
The <code>iteritems()</code> function returns an iterator over 
the dictionary’s (key, value) pairs.
</p>

<pre class="explanation">
for key in sorted(items.iterkeys(), reverse=True):
    print "%s: %s" % (key, items[key])
</pre>

<p>
In the second for loop, the data is sorted in descending order. 
The order type is controlled by the <code>reverse</code> parameter.
</p>

<pre>
$ ./sorting.py
bags: 1
books: 5
bottles: 4
coins: 7
cups: 2
pens: 3
####### #######
pens: 3
cups: 2
coins: 7
bottles: 4
books: 5
bags: 1
</pre>

<p>
Output of the sorting.py script. 
</p>

<hr class="btm">

<p>
In the next example, we are going to sort the items
by their values. 
</p>

<pre class="code">
#!/usr/bin/python

items = { "coins": 7, "pens": 3, "cups": 2, 
    "bags": 1, "bottles": 4, "books": 5 }
    
for key, value in sorted(items.iteritems(), 
    key=lambda (k,v): (v,k)):
        
    print "%s: %s" % (key, value) 

print "####### #######"    
    
for key, value in sorted(items.iteritems(), 
    key=lambda (k,v): (v,k), reverse=True):
         
    print "%s: %s" % (key, value)  
</pre>

<p>
The example prints the data in ascending and descending order
by their values. 
</p>

<pre class="explanation">
for key, value in sorted(items.iteritems(), 
    key=lambda (k,v): (v,k)):
</pre>

<p>
Dictionary pairs are sorted by their values and printed to 
the console. The key parameter takes a function, which indicates,
how the data is going to be sorted. 
</p>

<pre>
$ ./sorting2.py
bags: 1
cups: 2
pens: 3
bottles: 4
books: 5
coins: 7
####### #######
coins: 7
books: 5
bottles: 4
pens: 3
cups: 2
bags: 1
</pre>

<p>
From the output we can see, that this time the pairs were sorted according
to their values. 
</p>


<h2>Views</h2>

<p>
Python 2.7 introduced dictionary view objects. Views provide a dynamic
view on the items of a dictionary. They bear similarity to SQL views. 
When the dictionary changes, the view reflects these changes.
The <code>dict.viewkeys()</code>, <code>dict.viewvalues()</code> and 
<code>dict.viewitems()</code> methods return view objects. 
</p>

<p>
A view is a virtual read-only container. A view does not make a copy
of a dictionary. 
</p>

<pre class="code">
#!/usr/bin/python

fruits = { 'oranges': 12, 'pears': 5, 'apples': 4, 'bananas': 4 }

vi = fruits.viewitems()
vv = fruits.viewvalues()
vk = fruits.viewkeys()

for k, v in vi:
    print k, v

for v in vv:
    print v
    
for k in vk:
    print k
</pre>

<p>
Three view objects of the dictionary's items, dictionary's keys and 
dictionary's values are created. We traverse the view with the for loops.
</p>

<pre class="explanation">
vi = fruits.viewitems()
</pre>

<p>
The <code>viewitems()</code> creates a view of the dictionary's items. 
</p>

<pre class="explanation">
for k, v in vi:
    print k, v
</pre>

<p>
We traverse the created view and print the keys and values in
the for loop.
</p>


<pre>
$ ./views.py
bananas 4
pears 5
oranges 12
apples 4
4
5
12
4
bananas
pears
oranges
apples
</pre>

<p>
Output of the views.py script. 
</p>

<hr class="btm">

<p>
In the next example we show that a view reflects dictionary changes.
</p>

<pre class="code">
#!/usr/bin/python

fruits = { 'oranges': 12, 'pears': 5, 'apples': 4, 'bananas': 4}

vi = fruits.viewitems()

for k, v in vi:
    print k, v

fruits.pop('apples')
fruits.pop('oranges')

print "########### ##########"

for k, v in vi:
    print k, v
</pre>

<p>
A view is created on the fruits dictionary. Two items are deleted from
the dictionary. Then we traverse the view to see, if the changes are 
reflected. 
</p>

<pre class="explanation">
vi = fruits.viewitems()
</pre>

<p>
A view is created on the fruits dictionary.
</p>

<pre class="explanation">
fruits.pop('apples')
fruits.pop('oranges')
</pre>

<p>
Two items are deleted with the <code>pop()</code> method.
</p>

<pre class="explanation">
for k, v in vi:
    print k, v
</pre>

<p>
We loop through the view of the fruits. 
</p>


<pre>
$ ./views2.py
bananas 4
pears 5
oranges 12
apples 4
########### ##########
bananas 4
pears 5
</pre>

<p>
From the output we can see, that the changes were reflected
in the view. 
</p>


<p>
In this part of the Python tutorial, we have written about Python
dictionaries.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span>  ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified March 10, 2012  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

